package org.martyn.danbodroid.gui.activitys;

import org.martyn.danbodroid.DanboDroid;
import org.martyn.danbodroid.R;
import org.martyn.danbodroid.database.DatabaseHelper;
import org.martyn.danbodroid.database.ServersTable;
import org.martyn.danbooru.DanbooruConnectSettings;

import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

public class DanbooruPreferencesActivity extends PreferenceActivity implements OnPreferenceChangeListener
{
	public static final String DANBOORU_PREFERENCES_ACTIVITY_DATA_NAME = "danbooru_name";

	private static final String IP_ADDRESS_FORMAT = "[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}";
	private static final String HOST_NAME_FORMAT = "^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|\\b-){0,61}[0-9A-Za-z])?(?:\\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|\\b-){0,61}[0-9A-Za-z])?)*\\.?$";

	private EditTextPreference name;
	private EditTextPreference address;
	private ListPreference parseType;

	private DanbooruConnectSettings danbooruConnectSettings = null;
	private DatabaseHelper databaseHelper;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		DanboDroid danboDroid = (DanboDroid) this.getApplication();
		databaseHelper = danboDroid.getDatabaseHelper();
		
		int danbooruServerId = getIntent().getIntExtra(
				DANBOORU_PREFERENCES_ACTIVITY_DATA_NAME, 0);

		if (danbooruServerId != 0)
		{
			danbooruConnectSettings = ServersTable.get(databaseHelper, danbooruServerId);
		}
		else
		{
			danbooruConnectSettings = new DanbooruConnectSettings();
		}

		this.setPreferenceScreen(getPreferenceManager().createPreferenceScreen(
				this));

		initLayout();
		setPreferenceDescriptionTexts();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		boolean result = super.onCreateOptionsMenu(menu);

		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.danbooru_preferences_activity_menu, menu);
		return result;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item)
	{
		// Handle item selection
		switch (item.getItemId())
		{
			case R.id.menuItemCancel:
			{
				this.finish();
			}
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onPreferenceChange(Preference preference, Object newValue)
	{
		if (preference == name)
		{
			danbooruConnectSettings.name = (String) newValue;
		}
		else if (preference == address)
		{
			String newAddressValue = (String) newValue;

			// Validate for an IP address or host name
			String newAddress = (String) newValue;
			if (!(newAddress.matches(IP_ADDRESS_FORMAT) || newAddress
					.matches(HOST_NAME_FORMAT)))
			{
				Toast.makeText(getApplicationContext(),
						R.string.pref_danbooru_preferences_address_invalid,
						Toast.LENGTH_SHORT).show();

				return false;
			}

			danbooruConnectSettings.hostName = newAddressValue;
		}
		else if (preference == parseType)
		{
			String newParseType = (String) newValue;

			danbooruConnectSettings.danbooruParseType = newParseType;
		}

		updatePreferenceDescriptionText(preference, (String) newValue);

		return true;
	}

	@Override
	public void onBackPressed()
	{
		if (danbooruConnectSettings.hostName.trim().equals("")
				|| danbooruConnectSettings.name.trim().equals(""))
		{
			Toast.makeText(getApplicationContext(),
					R.string.pref_danbooru_preferences_empty,
					Toast.LENGTH_SHORT).show();
		}
		else
		{
			if (danbooruConnectSettings.id == 0)
			{
				danbooruConnectSettings.id = ServersTable.insert(databaseHelper,
						danbooruConnectSettings.name,
						danbooruConnectSettings.hostName,
						danbooruConnectSettings.danbooruParseType);
			}
			else
			{
				ServersTable.update(databaseHelper, danbooruConnectSettings.id,
						danbooruConnectSettings.name,
						danbooruConnectSettings.hostName,
						danbooruConnectSettings.danbooruParseType);

			}

			super.onBackPressed();
		}
	}

	private void initLayout()
	{
		// Name
		name = new EditTextPreference(this);
		name.setTitle(R.string.pref_danbooru_preferences_name);
		name.getEditText().setSingleLine();
		name.setDialogTitle(R.string.pref_danbooru_preferences_name);
		name.setOnPreferenceChangeListener(this);
		this.getPreferenceScreen().addItemFromInflater(name);

		// Address
		address = new EditTextPreference(this);
		address.setTitle(R.string.pref_danbooru_preferences_address);
		address.getEditText().setSingleLine();
		address.setDialogTitle(R.string.pref_danbooru_preferences_address);
		address.setOnPreferenceChangeListener(this);
		this.getPreferenceScreen().addItemFromInflater(address);

		// ParseType
		parseType = new ListPreference(this);
		parseType.setTitle(R.string.pref_danbooru_preferences_parsetype);
		parseType.setEntries(R.array.danbooru_preferences_parsetype_types);
		parseType.setEntryValues(R.array.danbooru_preferences_parsetype_values);
		parseType.setDialogTitle(R.string.pref_danbooru_preferences_parsetype);
		parseType.setOnPreferenceChangeListener(this);
		this.getPreferenceScreen().addItemFromInflater(parseType);
	}

	private void setPreferenceDescriptionTexts()
	{
		if (danbooruConnectSettings.id == 0)
		{
			name.setSummary(this
					.getString(R.string.pref_danbooru_preferences_name_no_name));
			address.setSummary(this
					.getText(R.string.pref_danbooru_preferences_address_no_junk));
			parseType
					.setSummary(DanbooruConnectSettings.DANBOORU_PARSE_TYPE_XML);
			parseType
					.setDefaultValue(DanbooruConnectSettings.DANBOORU_PARSE_TYPE_XML);
		}
		else
		{
			name.setSummary(danbooruConnectSettings.name);
			name.setText(danbooruConnectSettings.name);
			address.setSummary(danbooruConnectSettings.hostName);
			address.setText(danbooruConnectSettings.hostName);
			parseType.setSummary(danbooruConnectSettings.danbooruParseType);
			parseType.setValue(danbooruConnectSettings.danbooruParseType);
			// parseType
			// .setDefaultValue(danbooruConnectSettings.danbooruParseType);
		}
	}

	private void updatePreferenceDescriptionText(
			Preference preference,
			String summary)
	{
		preference.setSummary(summary);
	}

}
